import React, { useEffect, useState } from 'react';
import { TreeSelect, Spin } from 'antd';
import { companyGettree } from '@/services/Organization/staffmanage';
import { getUserOrgInfo } from '@/utils/utils';

const getTreeData = (data = [], fieldsName = { value: 'organizationCode', title: 'organizationName' }) =>
    data.map(item => ({
        ...item,
        value: item[fieldsName.value],
        title: item[fieldsName.title],
        key: item[fieldsName.value],
        children: item.children ? getTreeData(item.children, fieldsName) : item.children
    }));

const { SHOW_ALL } = TreeSelect;

const SelectComDepTree = ({ getChildByOrganizationCode, ...restProps }) => {
    const [treeData, setTreeData] = useState([]);
    const [loading, setLoading] = useState(true);
    const { firstCompanyPath } = getUserOrgInfo();
    // console.log('-----------------------------------', [...restProps.value]);

    /* 1、获取公司列表数据 */
    const fetchData = async () => {
        try {
            // const response = await companyGettree({ showTreeFlag: 1, getChildByOrganizationCode });
            const response = await companyGettree({
                showTreeFlag: 1,
                parentOrgPathListHasSelf: firstCompanyPath
            });
            if (response.code === 10000) {
                /* 2、将数据转换为树选择组件所需格式 */
                const finalTreeData = getTreeData(response.data);
                setTreeData(finalTreeData);
            }
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    return (
        <Spin spinning={loading}>
            <TreeSelect treeData={treeData} showCheckedStrategy={SHOW_ALL} maxTagCount={10} {...restProps} />
        </Spin>
    );
};

export default SelectComDepTree;
